<?php

namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Helpers\Helper;
use App\Helpers\RedisUtil;
use App\Helpers\StringUtil;
use App\Model\User;
use App\Model\UncodePhoneSettings;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;

/**
 * 验证码获取
 */
class CaptchaGetService extends BaseService
{
    protected $captchaTimes = 20;

    public function handle()
    {
        $phone = $this->request->input('phone', '');
        $appId = $this->request->input('appid', 1);
        $channel = $this->request->input('channel', 1);
//        return [
//            'result' => 1,
//            'msg' => '验证码已经成功发送至该手机号！',
//            'captcha_times' => 1,
//            'white' => 1
	//        ];
	//        
        //查找用户是否存在
        $user = User::checkPhone($phone);
        //账号被冻结
        if ($user && $user->status == User::STATUS_FREEZE) {
            return $this->setError(ErrorCode::USER_NOT_VALID, '该用户涉嫌违规已被冻结账号！');
        }
	//查看是否免认证手机号
        $UncodePhone = UncodePhoneSettings::checkUncodePhone($phone);

        //测试环境，且不在测试白名单中
        //线上环境，且在百白名单
        if ((check_dev_env() && !$this->checkDevPhone($phone))  || $this->checkWhitePhone($phone) || $UncodePhone) {
            return [
                'result' => 1,
                'msg' => '验证码已经成功发送至该手机号！',
                'captcha_times' => 1,
		'white' => 1,
	        'uncode_phone' => 1
            ];
        }

        //检测手机号合法
        if (StringUtil::isStrValid($phone, StringUtil::MobileString) == false) {
            return $this->setError(ErrorCode::PARAMETER_ERROR);
        }
        //验证码次数
        $timesKey = 'CaptchaGetTimes_' . date('Ymd');
        $times = RedisUtil::hget($timesKey, $phone);
        if (!check_dev_env() && $times >= $this->captchaTimes) {
            return $this->setError(ErrorCode::CAPTCHA_LMT, '今天获取验证码的次数已用完啦~');
        }
        //设置次数缓存
        RedisUtil::hset($timesKey, $phone, intval($times) + 1);

        $captcha = '8888';
        if (!check_dev_env()) {
            //验证码获取并缓存
            $captcha = Helper::getCaptcha($phone);
            //发送验证码
            $result = Helper::sendCaptcha($phone, $captcha, $appId,$channel);
        }

        return [
            'result' => 1,
            'msg' => '验证码已经成功发送至该手机号！',
            'captcha_times' => $times,
            // 'phone' => $phone,
            // 'captcha' => $captcha
        ];
    }


    /**
     * 白名单手机号
     */
    function checkDevPhone($phone = '')
    {
        $valid = ['18826565510'];
        return in_array($phone, $valid);
    }
}
